package com.yuliang.ai.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuliang.ai.domain.Dto.AreaDto;
import com.yuliang.ai.domain.Dto.HotelStarDto;
import com.yuliang.ai.domain.Dto.TourCommonDto;
import com.yuliang.ai.domain.Vo.HotelVo;
import com.yuliang.ai.service.HotelService;
import com.yuliang.utils.result.ResultUtils;
import com.yuliang.utils.result.emums.HttpCodeEnum;
import com.yuliang.utils.util.HttpRequestUtils;
import com.yuliang.utils.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Huangkai
 */
@Slf4j
@Service
public class HotelServiceImpl implements HotelService {

    @Value("${spring.requestUrl}")
    private String requestUrl;

    @Override
    public TourCommonDto selectHotelInfo(HotelVo hotelVo)  {
        try {
            String requestPath = requestUrl + "/app/json/ela_search/getHotelsWithFilter";
            Map<String, Object> mapParam = new HashMap<>(4);
            //城市非空
            if (StringUtils.isNotEmpty(hotelVo.getCity())) {
                mapParam.put("city", hotelVo.getCity());
            }
            if (StringUtils.isNotEmpty(hotelVo.getKeyWord())) {
                mapParam.put("keyWord", hotelVo.getKeyWord());
            }
            if (hotelVo.getMaxPrice() != null) {
                mapParam.put("maxPrice", hotelVo.getMaxPrice());
            }
            if (hotelVo.getMinPrice() != null) {
                mapParam.put("minPrice", hotelVo.getMinPrice());
            }
            if(StringUtils.isNotEmpty(hotelVo.getBrand())){
                mapParam.put("brand", hotelVo.getBrand());
            }
            if(StringUtils.isNotEmpty(hotelVo.getMeals())){
                mapParam.put("meals", hotelVo.getMeals());
            }
            if(StringUtils.isNotEmpty(hotelVo.getTheme())){
                mapParam.put("theme", hotelVo.getTheme());
            }

            mapParam.put("searchPage", hotelVo.getSearchPage());
            mapParam.put("searchSize", hotelVo.getSearchSize());
            Map<String, String> header = new HashMap<>(2);
            header.put("referrer", "c:app::0EDDDEEF167C465A8DAD5CD36C5A1C73");
            String result = HttpRequestUtils.doPost(requestPath, header, mapParam);
            JSONObject resultObject = JSONObject.parseObject(result);
            Integer status = resultObject.getInteger("status");
            if (status == 0) {
                if (resultObject.containsKey("data")) {
                    JSONObject resultDataObject = resultObject.getJSONObject("data");
                    TourCommonDto hotelListDto = resultDataObject.toJavaObject(TourCommonDto.class);
                    List<TourCommonDto.ElaSearchListModel> elaSearchListModels = hotelListDto.getElaSearchListModels();
                    if(elaSearchListModels != null && elaSearchListModels.size() > 0){
                        TourCommonDto.ElaSearchListModel elaSearchListModel = elaSearchListModels.stream().findFirst().get();
                        List<TourCommonDto.JumpLink> jumpLinks = elaSearchListModel.getJumpLinks();
                        //使用第一个跳转
                        TourCommonDto.JumpLink jumpLink = jumpLinks.get(1);
                        String url = jumpLink.getUrl();
                        url = url + "&sCode=SJZY&sName=" + URLEncoder.encode("三姐助游", "UTF-8");
                        jumpLink.setUrl(url);
                        return hotelListDto;
                    }
                }
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    @Override
    public List<AreaDto> selectCityList() {
        String url = requestUrl + "/app/json/ela_search/queryDestinationArea";
        JSONObject jsonObject = new JSONObject();
        Map<String, String> header = new HashMap<>(2);
        header.put("referrer", "c:app::0EDDDEEF167C465A8DAD5CD36C5A1C73");
        String result = HttpRequestUtils.doPost(url, header, jsonObject.toJSONString());
        JSONObject resultObject = JSONObject.parseObject(result);
        Integer status = resultObject.getInteger("status");
        if(status == 0){
            JSONArray jsonArray = resultObject.getJSONArray("data");
            List<AreaDto> areaDtoList = jsonArray.toJavaList(AreaDto.class);
            List<AreaDto> firstAreaDtoList = areaDtoList.stream().filter(firstAreaDto -> firstAreaDto.getLevel().equals("1")).collect(Collectors.toList());
            if(firstAreaDtoList != null && firstAreaDtoList.size() > 0){
                firstAreaDtoList.forEach(areaDto -> {
                    List<AreaDto> twoAreaDtoList = areaDtoList.stream().filter(twoAreaDto -> twoAreaDto.getParentId().equals(areaDto.getKey())).collect(Collectors.toList());
                    areaDto.setChildrenList(twoAreaDtoList);
                });
            }
            return areaDtoList;
        }
        return null;
    }

    @Override
    public String selectHotelPriceStar() {
        String url = requestUrl + "/app/json/ela_search/queryHotelPriceAndLevel";
        JSONObject jsonObject = new JSONObject();
        Map<String, String> header = new HashMap<>(2);
        header.put("referrer", "c:app::0EDDDEEF167C465A8DAD5CD36C5A1C73");
        String result = HttpRequestUtils.doPost(url, header, jsonObject.toJSONString());
        JSONObject resultObject = JSONObject.parseObject(result);
        Integer status = resultObject.getInteger("status");
        if(status == 0){
            JSONObject object = resultObject.getJSONObject("data");
            HotelStarDto hotelStarDto = object.toJavaObject(HotelStarDto.class);
            log.info("酒店星级数据{}", hotelStarDto);
            return ResultUtils.ResultWithMessageDataEnum(HttpCodeEnum.select_success, hotelStarDto);
        }
        return ResultUtils.ResultWithMessageEnum(HttpCodeEnum.data_not_exist);
    }

    /**
     * 获取树层级
     * @param treeList
     * @param parentId
     * @return
     */
    public List<AreaDto> streamToTree(List<AreaDto> treeList, String parentId) {
        List<AreaDto> list = treeList.stream()
                // 过滤父节点
                .filter(parent -> parent.getParentId().equals(parentId))
                // 把父节点children递归赋值成为子节点
                .map(child -> {
                    child.setChildrenList(streamToTree(treeList, child.getKey()));
                    return child;
                }).collect(Collectors.toList());
        return list;
    }
}
